package face.pay.cpn.cpnStatistics.impl;

import face.pay.cpn.cpnStatistics.ICpnStatisticsService;
import face.pay.dao.CpnStatisticsDao;
import face.pay.entity.CpnStatistics;
import face.pay.entity.UserInfo;
import face.pay.util.DateUtil;
import face.pay.util.ResultMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @Auther: cjj
 * @Date: 2020/2/12
 * @Description:
 */
@Service
public class CpnStatisticsServiceImpl implements ICpnStatisticsService {

    @Autowired
    private CpnStatisticsDao cpnStatisticsDao;


    @Override
    public ResultMessage getStatistics(UserInfo loginUser, String queryTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String pattern = "yyyy年MM月dd日";
        Date date = null;
        if (StringUtils.isBlank(queryTime)) {
            date = new Date();
        } else {
            date = DateUtil.dateParse(queryTime, pattern);
        }
        String startTime = sdf.format(getStartOfDay(date));
        String endTime = sdf.format(getEndOfDay(date));

        CpnStatistics cpn = new CpnStatistics();
        cpn.setActivitys(cpnStatisticsDao.queryActivitys(loginUser.getId()));
        cpn.setCpns(cpnStatisticsDao.queryCpns(loginUser.getId()));
        cpn.setCpnGets(cpnStatisticsDao.queryCpnGets(loginUser.getId(), startTime, endTime));
        cpn.setCpnNotGets(cpnStatisticsDao.queryCpnNotGets(loginUser.getId(), startTime, endTime));
        cpn.setCpnCancels(cpnStatisticsDao.queryCpnCancels(loginUser.getId(), startTime, endTime));
        return ResultMessage.createSuccess(cpn);
    }


    // 获得某天最大时间
    private Date getEndOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        ;
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    // 获得某天最小时间
    private Date getStartOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

}
